package com.android.core.network;

import android.text.TextUtils;

import com.android.core.base.BaseApplication;
import com.android.core.utils.log.Logger;

import java.io.File;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RestApi {
    public static boolean isDebug = true;

    // create retrofit singleton
    private Retrofit createApiClient(String baseUrl) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(createOkHttpClient(isDebug))
                .build();
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final RestApi INSTANCE = new RestApi();

        private SingletonHolder() {
            throw new UnsupportedOperationException("u can't instantiate SingletonHolder...");
        }
    }

    public static synchronized RestApi getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public void deBug(boolean isDebug) {
        this.isDebug = isDebug;
    }


    // create api service singleton
    public <T> T create(String baseUrl, Class<T> clz) {
        String serviceUrl = "";
        try {
            Field field1 = clz.getField("BASE_URL");
            serviceUrl = (String) field1.get(clz);
        } catch (Exception e) {
            Logger.i("exception", e);
        }
        return createApiClient(
                TextUtils.isEmpty(serviceUrl) ? baseUrl : serviceUrl).create(clz);
    }

    // create api service baseUrl singleton
    public <T> T create(Class<T> clz) {
        String serviceUrl = "";
        try {
            Field field1 = clz.getField("BASE_URL");
            serviceUrl = (String) field1.get(clz);
            if (TextUtils.isEmpty(serviceUrl)) {
                throw new NullPointerException("base_url is null");
            }
        } catch (Exception e) {
            Logger.i("exception", e);
        }
        return createApiClient(serviceUrl).create(clz);
    }

    // create okHttpClient singleton
    private OkHttpClient createOkHttpClient(boolean debug) {
        //缓存
        int size = 1024 * 1024 * 100;
        File cacheFile = new File(BaseApplication.getContext().getCacheDir(), "OkHttpCache");
        Cache cache = new Cache(cacheFile, size);

        return new OkHttpClient.Builder()
                .connectTimeout(12, TimeUnit.SECONDS)
                .writeTimeout(12, TimeUnit.SECONDS)
                .addNetworkInterceptor(new HttpCacheInterceptor())
//                .addInterceptor(new HttpLoggingInterceptor().setLevel(
//                        debug ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE))
                .addInterceptor(new LoggingInterceptor())
                .cache(cache)
                .build();

    }
}
